package com.taichuan.selfcheck.ui.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.taichuan.camera.CameraIdTypeUtils;
import com.taichuan.camera.TcCameraVariable;
import com.taichuan.camera.TcTextureViewCameraUtils;
import com.taichuan.camera.VankeSiteBoxCameraIdTypeUtils;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.SelfCheckAppModuleConfig;
import com.taichuan.selfcheck.config.PropertyDefaultValue;
import com.taichuan.selfcheck.hardware.LightControlUtils;
import com.taichuan.selfcheck.mvp.presenter.TestCameraPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.TestCameraInterface;
import com.taichuan.selfcheck.ui.dialog.ResultDialog;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.tcutils.taichuan.SystemUtils;
import com.taichuan.tcutils.taichuan.TcDeviceType;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2020/4/2
 */
public class TestDoubleCameraFragment extends AppBaseFragment<TestCameraInterface, TestCameraPresenter> implements TestCameraInterface{
    private static final String TAG = TestDoubleCameraFragment.class.getSimpleName();

    public static final int CAMERA_TYPE_COLOR = 0;         //彩色摄像头
    public static final int CAMERA_TYPE_INFRARED = 1;     //红外摄像头
    public static final int CAMERA_TYPE_TAKE_PHOTO = 2;     //万科智慧工地项目-拍单摄像头

    private static final int REFRESH_CAMERA_INIT_INFO = 1;              //更新相机初始化耗时信息
    private static final int REFRESH_COLOR_CAMERA_PARMA_INFO = 2;       //更新彩色相机参数信息
    private static final int REFRESH_INFRAD_CAMERA_PARMA_INFO = 3;      //更新红外相机参数信息
    private static final int REFRESH_TAKE_PHOTO_CAMERA_PARMA_INFO = 4;      //更新拍单相机参数信息
    private static final int REFRESH_CAMERA_CALLBACK_DATA_INFO = 5;     //更新相机数据回调信息
    private static final int MSG_COLOR_CAMERA_ERROR = 6;                    //彩色摄像头出现异常
    private static final int MSG_INFRARD_CAMERA_ERROR = 7;                   //黑白摄像头出现异常
    private static final int MSG_TAKE_PHOTO_CAMERA_ERROR = 8;                   //黑白摄像头出现异常

    /**
     * 人脸识别时摄像头出现异常的 超时判定时间为 2秒
     */
    private static final int CAMERA_ERROR_TIMEOUT_TIME = 2 * 1000;

    /**
     * 定义一组变量用于控制预览画面的分辨率宽高，如不知道可都先填0，程序会自动使用默认的分辨率配置
     */
    private static final int PREVIEW_IMAGE_WIDTH = 1280;
    private static final int PREVIEW_IMAGE_HEIGHT = 720;

    /**
     * 定义一组变量用于控制预览画面的分辨率宽高，如不知道可都先填0，程序会自动使用默认的分辨率配置
     * 万科智慧工地 拍单摄像头 专用
     */
    private static final int PREVIEW_IMAGE_WIDTH_FOR_TAKE_PHOTO = 2560;
    private static final int PREVIEW_IMAGE_HEIGHT_FOR_TAKE_PHOTO = 1440;

    @BindView(R.id.activity_test_camera_start_preview_button)
    Button startPreviewButton;
    @BindView(R.id.activity_test_camera_stop_preview_button)
    Button stopPreviewButton;
    @BindView(R.id.color_camera_content_layout)
    RelativeLayout colorCameraContentLayout;
    @BindView(R.id.camera_data_callback_switch)
    Switch dataCallbackCb;
    @BindView(R.id.activity_test_double_camera_color_init_info_textView)
    TextView colorCameraInitInfoTv;
    @BindView(R.id.activity_test_double_camera_color_parma_textView)
    TextView colorCameraParmaTv;

    @BindView(R.id.infrad_camera_content_layout)
    RelativeLayout infradCameraContentLayout;
    @BindView(R.id.activity_test_double_camera_infrad_init_info_textView)
    TextView infradCameraInitInfoTv;
    @BindView(R.id.activity_test_double_camera_infrad_parma_textView)
    TextView infradCameraParmaTv;
    @BindView(R.id.activity_test_double_camera_color_delay_time_textView)
    TextView colordelayTimeTv;
    @BindView(R.id.activity_test_double_camera_infrad_delay_time_textView)
    TextView infraddelayTimeTv;

    @BindView(R.id.take_photo_camera_content_layout)
    RelativeLayout takePhotoCameraContentLayout;
    @BindView(R.id.activity_test_double_camera_take_photo_init_info_textView)
    TextView takePhotoCameraInitInfoTv;
    @BindView(R.id.activity_test_double_camera_take_photo_parma_textView)
    TextView takePhotoCameraParmaTv;
    @BindView(R.id.activity_test_double_camera_take_photo_delay_time_textView)
    TextView takePhotoDelayTimeTv;

    private TcTextureViewCameraUtils colorCameraUtils;
    private TcTextureViewCameraUtils infradCameraUtils;
    private TcTextureViewCameraUtils takePhotoCameraUtils;

    private TextureView colorCameraPreviewView;
    private TextureView infradCameraPreviewView;
    private TextureView takePhotoCameraPreviewView;

    private ColorCameraPreviewCallback colorCameraPreviewCallback;
    private InfradCameraPreviewCallback infradCameraPreviewCallback;
    private TakePhotoCameraPreviewCallback takePhotoCameraPreviewCallback;

    /**
     * 定义一个变量用于记录 彩色摄像头 开始调用 初始化函数前的时间
     */
    private long colorCameraInitStartTime;
    /**
     * 定义一个变量用于记录 彩色摄像头 调用 初始化函数 的执行时间
     */
    private long colorCameraInitTime;
    /**
     * 定义一个变量用于记录 彩色摄像头 【初始化结束】后 到 接收到第一帧数据回调 的执行时间
     */
    private long colorCameraGetDataTime;
    /**
     * 定义一个变量用于记录 彩色摄像头 初始化开始 到 接收到第一帧数据回调 的执行时间
     */
    private long colorCameraInitTotalTime;

    /**
     * 定义一个变量用于记录 彩色摄像头 上一帧数据回调 的获取时间
     */
    private long lastColorCameraPreviewDataTime;

    /**
     * 定义一个变量用于记录是否为 彩色摄像头 第一次接收到相机数据回调
     */
    private boolean isColorCameraFristDataCallback = true;

    /**
     * 定义一个变量用于记录 红外摄像头 开始调用 初始化函数前的时间
     */
    private long infradCameraInitStartTime;
    /**
     * 定义一个变量用于记录 红外摄像头 调用 初始化函数 的执行时间
     */
    private long infradCameraInitTime;
    /**
     * 定义一个变量用于记录 红外摄像头 【初始化结束】后 到 接收到第一帧数据回调 的执行时间
     */
    private long infradCameraGetDataTime;
    /**
     * 定义一个变量用于记录 红外摄像头 初始化开始 到 接收到第一帧数据回调 的执行时间
     */
    private long infradCameraInitTotalTime;

    /**
     * 定义一个变量用于记录 红外摄像头 上一帧数据回调 的获取时间
     */
    private long lastInfradCameraPreviewDataTime;

    /**
     * 定义一个变量用于记录是否为 红外摄像头 第一次接收到相机数据回调
     */
    private boolean isInfradCameraFristDataCallback = true;

    /**
     * 定义一个变量用于记录 拍单摄像头 开始调用 初始化函数前的时间
     */
    private long takePhotoCameraInitStartTime;
    /**
     * 定义一个变量用于记录 拍单摄像头 调用 初始化函数 的执行时间
     */
    private long takePhotoCameraInitTime;
    /**
     * 定义一个变量用于记录 拍单摄像头 【初始化结束】后 到 接收到第一帧数据回调 的执行时间
     */
    private long takePhotoCameraGetDataTime;
    /**
     * 定义一个变量用于记录 拍单摄像头 初始化开始 到 接收到第一帧数据回调 的执行时间
     */
    private long takePhotoCameraInitTotalTime;

    /**
     * 定义一个变量用于记录 红外摄像头 上一帧数据回调 的获取时间
     */
    private long lastTakePhotoCameraPreviewDataTime;

    /**
     * 定义一个变量用于记录是否为 拍单摄像头 第一次接收到相机数据回调
     */
    private boolean isTakePhotoCameraFristDataCallback = true;

    /**
     * 定义一个变量用于控制 是否需要数据回调
     */
    private boolean isNeedDataCallback = true;

    /**
     * 定义一个变量用于控制 是否处于重置状态
     */
    private boolean isInResetUsbCamera = false;
    private ResultDialog resultDialog;


    @Override
    protected TestCameraPresenter createPresenter() {
        return new TestCameraPresenter(getActivity());
    }

    @Override
    public void refreshTakePhotoView(Bitmap cameraBitmap) {

    }

    @Override
    public int getCameraType() {
        return 0;
    }

    @Override
    public String getCameraTypeName() {
        return null;
    }

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
//        mViewFocus.nextFocus();     //TODO 特殊处理，因为大体框架已经下好  所有功能页面统一按 * 号键返回主页面， 此时与自定义控件KSSpinner 内部的 * 号键- - -选择子项 功能冲突，
        // TODO 为避免再退出时再次切换分辨率，在从Activity层下发到Fragment层前，将KSSpinner控件的焦点移除
        resultDialog.show();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_1:
                startPreviewButton.performClick();
                break;
            case KeyEvent.KEYCODE_2:
                stopPreviewButton.performClick();
                break;
            case KeyEvent.KEYCODE_3:
                dataCallbackCb.setChecked(!dataCallbackCb.isChecked());
                break;
        }
        if (resultDialog.isShowing()) {
            resultDialog.dispatchKeyEvent(event);
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    protected int setContentViewId() {
        if (SystemUtils.getTcDeviceType() == TcDeviceType.A33_LANDSCAPE_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.A64_LANDSCAPE_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.L10_Pro ||
                SystemUtils.getTcDeviceType() == TcDeviceType.RK3399_LANDSCAPE_KEY) {          //横屏 设备
            return R.layout.fragment_double_camera_test_land;
        }else {
            if (!SystemUtils.isVankeSiteBoxDevice()){           //普通竖屏设备
                return R.layout.fragment_double_camera_test;
            }else {                                             //万科智慧工地项目设备
                return R.layout.fragment_third_camera_test;
            }
        }
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        //初始化CheckBox
        initCheckBox();
        //初始化摄像头预览控件
        initPreviewView();
        //开启红外灯
        LightControlUtils.getInstance().openOrCloseInfraredLight(true);

        String tittle = "";
        //初始化摄像头工具类
        if (!SystemUtils.isVankeSiteBoxDevice()){           //常规设备
            initCamera();
            tittle = getResources().getString(R.string.double_camera_test);
        }else {                                             //万科智慧工地项目设备
            initCameraForVankeSiteBox();
            tittle = getResources().getString(R.string.third_camera_test);
        }
        //初始化测试结果Dialog
        resultDialog = new ResultDialog(PropertyDefaultValue.FUNCTION_TEST_15,tittle, getActivity());       //设置弹窗发送的事件——摄像头测试
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //关闭红外灯
        LightControlUtils.getInstance().openOrCloseInfraredLight(false);
    }

    private void initCheckBox() {
        dataCallbackCb.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isNeedDataCallback = isChecked;
            if (isNeedDataCallback) {
                colorCameraUtils.setPreviewCallback(colorCameraPreviewCallback);
                infradCameraUtils.setPreviewCallback(infradCameraPreviewCallback);
                if (takePhotoCameraUtils != null){
                    takePhotoCameraUtils.setPreviewCallback(takePhotoCameraPreviewCallback);
                }
            } else {
                colorCameraUtils.setPreviewCallback(null);
                infradCameraUtils.setPreviewCallback(null);
                if (takePhotoCameraUtils != null){
                    takePhotoCameraUtils.setPreviewCallback(null);
                }
            }
        });

        isColorCameraFristDataCallback = true;
        isInfradCameraFristDataCallback = true;
        isTakePhotoCameraFristDataCallback = true;
    }

    private void initPreviewView() {
        //创建彩色摄像头预览显示控件
        RelativeLayout.LayoutParams colorParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        colorCameraPreviewView = new TextureView(getActivity());
        //设置TextureView状态监听
        colorCameraPreviewView.setSurfaceTextureListener(new ColorCameraTextureListener());
        //将预览控件添加到布局中
        colorCameraContentLayout.addView(colorCameraPreviewView, colorParams);

        //创建红外摄像头预览显示控件
        RelativeLayout.LayoutParams infradParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        infradCameraPreviewView = new TextureView(getActivity());
        //设置TextureView状态监听
        infradCameraPreviewView.setSurfaceTextureListener(new InfradCameraTextureListener());
        //将预览控件添加到布局中
        infradCameraContentLayout.addView(infradCameraPreviewView, infradParams);

        if (SystemUtils.isVankeSiteBoxDevice()){
            //创建红外摄像头预览显示控件
            RelativeLayout.LayoutParams takePhotoParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            takePhotoCameraPreviewView = new TextureView(getActivity());
            //设置TextureView状态监听
            takePhotoCameraPreviewView.setSurfaceTextureListener(new TakePhotoCameraTextureListener());
            //将预览控件添加到布局中
            takePhotoCameraContentLayout.addView(takePhotoCameraPreviewView, takePhotoParams);
        }
    }

    private void initCamera() {
        //刷新获取摄像头下标，防止设备因极端情况下（静电，摄像头异常，手动开关USB摄像头操作） 导致摄像头下标混乱
        CameraIdTypeUtils.getInstance().checkCheShenCameraIdType();
        //实例化彩色相机工具类
        colorCameraUtils = new TcTextureViewCameraUtils(getActivity(), colorCameraPreviewView.getSurfaceTexture(),
                SelfCheckAppModuleConfig.getCameraPreviewOration(),TAG + "_color");
        colorCameraUtils.setOpenCameraId(CameraIdTypeUtils.getInstance().getColorCameraId(), TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_COLOR,
                TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_DOUBLE);

        //设置预览分辨率
        colorCameraUtils.setPreviewViewSize(PREVIEW_IMAGE_WIDTH, PREVIEW_IMAGE_HEIGHT);
        colorCameraPreviewCallback = new ColorCameraPreviewCallback();


        //实例化红外相机工具类
        infradCameraUtils = new TcTextureViewCameraUtils(getActivity(), infradCameraPreviewView.getSurfaceTexture(),
                SelfCheckAppModuleConfig.getCameraPreviewOration(),TAG + "_infrad");
        if (SystemUtils.getTcDeviceType() == TcDeviceType.RK3399_VERTICAL_TOUCH_O8A_DOOR){
            infradCameraUtils.setOpenCameraId(CameraIdTypeUtils.getInstance().getInfraredCameraId(),TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_INFRARD,
                    TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_DOUBLE_WITH_AUTO_INFRARD_LIGHT);
            Log.e(TAG, "initCamera: 当前打开的为 TC-Y9D-O8A 设备的红外摄像头");
        }else {
            infradCameraUtils.setOpenCameraId(CameraIdTypeUtils.getInstance().getInfraredCameraId(),TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_INFRARD,
                    TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_DOUBLE);
        }

        //设置预览分辨率
        infradCameraUtils.setPreviewViewSize(PREVIEW_IMAGE_WIDTH, PREVIEW_IMAGE_HEIGHT);
        infradCameraPreviewCallback = new InfradCameraPreviewCallback();
    }


    private void initCameraForVankeSiteBox() {
        //刷新获取摄像头下标，防止设备因极端情况下（静电，摄像头异常，手动开关USB摄像头操作） 导致摄像头下标混乱
        VankeSiteBoxCameraIdTypeUtils.getInstance().checkVankeSiteBoxCameraIdType();
        //实例化彩色相机工具类
        colorCameraUtils = new TcTextureViewCameraUtils(getActivity(), colorCameraPreviewView.getSurfaceTexture(),
                SelfCheckAppModuleConfig.getCameraPreviewOration(),TAG + "_color");
        colorCameraUtils.setOpenCameraId(VankeSiteBoxCameraIdTypeUtils.getInstance().getColorCameraId(), TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_COLOR,
                TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_MULTI);

        //设置预览分辨率
        colorCameraUtils.setPreviewViewSize(PREVIEW_IMAGE_WIDTH, PREVIEW_IMAGE_HEIGHT);
        colorCameraPreviewCallback = new ColorCameraPreviewCallback();

//-----------------------------------------------红外摄像头---------------------------------------------------------
        //实例化红外相机工具类
        infradCameraUtils = new TcTextureViewCameraUtils(getActivity(), infradCameraPreviewView.getSurfaceTexture(),
                SelfCheckAppModuleConfig.getCameraPreviewOration(),TAG + "_infrad");
            infradCameraUtils.setOpenCameraId(VankeSiteBoxCameraIdTypeUtils.getInstance().getInfraredCameraId(),TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_INFRARD,
                    TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_MULTI);

        //设置预览分辨率
        infradCameraUtils.setPreviewViewSize(PREVIEW_IMAGE_WIDTH, PREVIEW_IMAGE_HEIGHT);
        infradCameraPreviewCallback = new InfradCameraPreviewCallback();

//-----------------------------------------------拍单摄像头---------------------------------------------------------
        //实例化拍单相机工具类
        takePhotoCameraUtils = new TcTextureViewCameraUtils(getActivity(), takePhotoCameraPreviewView.getSurfaceTexture(),
                SelfCheckAppModuleConfig.getCameraPreviewOration(),TAG + "_takePhoto");
        takePhotoCameraUtils.setOpenCameraId(VankeSiteBoxCameraIdTypeUtils.getInstance().getTakePhotoCameraId(),TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_TAKE_PHOTO,
                TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_MULTI);

        //设置预览分辨率
        takePhotoCameraUtils.setPreviewViewSize(PREVIEW_IMAGE_WIDTH_FOR_TAKE_PHOTO, PREVIEW_IMAGE_HEIGHT_FOR_TAKE_PHOTO);
        takePhotoCameraPreviewCallback = new TakePhotoCameraPreviewCallback();
    }

    @OnClick({R.id.activity_test_camera_start_preview_button,
            R.id.activity_test_camera_stop_preview_button})
    @Override
    public void onXmlClick(View v) {
        super.onXmlClick(v);
        if (v.getId() == R.id.activity_test_camera_start_preview_button){           //开始预览
            startPreview();
        }else if (v.getId() == R.id.activity_test_camera_stop_preview_button){      //关闭预览
            //停止预览并注销摄像头
            stopPreviewAndDestoryCamera();
            resetState();
        }
    }

    /**
     * 定义一个方法用于开始执行摄像头预览
     */
    private void startPreview() {
        //刷新获取摄像头下标，防止设备因极端情况下（静电，摄像头异常，手动开关USB摄像头操作） 导致摄像头下标混乱
        if (!SystemUtils.isVankeSiteBoxDevice()){
            refreshCameraIdAndUtils();
        }else {
            refreshCameraIdAndUtilsForVankeSiteBox();
        }

        //初始化摄像头并开始预览
        if (!SystemUtils.isVankeSiteBoxDevice()){           //普通RK3399设备
            initColorCameraAndPreview(colorCameraPreviewView.getSurfaceTexture());
            initInfradCameraAndPreview(infradCameraPreviewView.getSurfaceTexture());
        }else {
            //先打开彩色摄像头，执行完毕后再打开红外摄像头，执行完毕后再打开拍单摄像头
            initColorCameraAndPreview(colorCameraPreviewView.getSurfaceTexture());
        }

        //开启红外补光灯
        LightControlUtils.getInstance().openOrCloseInfraredLight(true);
    }

    /**
     * 定义一个方法用于刷新获取摄像头下标，并更新相机工具类的cameraID下标
     */
    private void refreshCameraIdAndUtils() {
        //刷新获取摄像头下标，防止设备因极端情况下（静电，摄像头异常，手动开关USB摄像头操作） 导致摄像头下标混乱
        CameraIdTypeUtils.getInstance().checkCheShenCameraIdType();
        //更新相机工具类的CameraId下标
        colorCameraUtils.setOpenCameraId(CameraIdTypeUtils.getInstance().getColorCameraId(), TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_COLOR,
                TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_DOUBLE);

        if (SystemUtils.getTcDeviceType() == TcDeviceType.RK3399_VERTICAL_TOUCH_O8A_DOOR){
            infradCameraUtils.setOpenCameraId(CameraIdTypeUtils.getInstance().getInfraredCameraId(),TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_INFRARD,
                    TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_DOUBLE_WITH_AUTO_INFRARD_LIGHT);
            Log.e(TAG, "refreshCameraIdAndUtils: 当前打开的为 TC-Y9D-O8A 设备的红外摄像头");
        }else {
            infradCameraUtils.setOpenCameraId(CameraIdTypeUtils.getInstance().getInfraredCameraId(),TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_INFRARD,
                    TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_DOUBLE);
        }
    }

    /**
     * 定义一个方法用于刷新获取摄像头下标，并更新相机工具类的cameraID下标
     */
    private void refreshCameraIdAndUtilsForVankeSiteBox() {
        //刷新获取摄像头下标，防止设备因极端情况下（静电，摄像头异常，手动开关USB摄像头操作） 导致摄像头下标混乱
        VankeSiteBoxCameraIdTypeUtils.getInstance().checkVankeSiteBoxCameraIdType();
        //更新相机工具类的CameraId下标
        colorCameraUtils.setOpenCameraId(VankeSiteBoxCameraIdTypeUtils.getInstance().getColorCameraId(), TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_COLOR,
                TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_MULTI);
        infradCameraUtils.setOpenCameraId(VankeSiteBoxCameraIdTypeUtils.getInstance().getInfraredCameraId(),TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_INFRARD,
                TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_MULTI);
        takePhotoCameraUtils.setOpenCameraId(VankeSiteBoxCameraIdTypeUtils.getInstance().getTakePhotoCameraId(),TcCameraVariable.CameraIdType.CAMERA_ID_TYPE_TAKE_PHOTO,
                TcCameraVariable.CameraDeviceMode.CAMERA_DEVICE_MODE_MULTI);
    }

    /**
     * 定义一个方法用于初始化摄像头，并开启预览
     */
    @SuppressLint("CheckResult")
    private void initColorCameraAndPreview(final SurfaceTexture surface) {
        Observable.just("")
                .observeOn(Schedulers.io())
                .map(new Function<String, Integer>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public Integer apply(String s) {
                        //初始化摄像头
                        colorCameraInitStartTime = System.currentTimeMillis();
                        Log.e(TAG, "apply: ----------开始执行 彩色摄像头初始化流程,执行的CameraId下标为： " + colorCameraUtils.getOpenCameraId()
                                + "  当前毫秒数：  " + colorCameraInitStartTime);
                        int initResult;
                        if (!SystemUtils.isVankeSiteBoxDevice()){           //普通设备
                            initResult = colorCameraUtils.initCamera();
                        }else {                                             //万科智慧工地项目设备
                            initResult = colorCameraUtils.initCamera(false);
                        }
                        colorCameraInitTime = System.currentTimeMillis() - colorCameraInitStartTime;
                        Log.e(TAG, "apply: ----------完成 彩色摄像头初始化流程。【【【总共耗时：  " + colorCameraInitTime);
                        return initResult;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer initResult) {
                        try {
                            Log.e(TAG, "accept: 彩色摄像头初始化结果：  " + initResult);
                            //如果摄像头初始化成功或者已经初始化过了，就执行预览流程
                            if (initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_INIT_SUCESS ||
                                    initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_INITED){
                                //初始化摄像头成功，将标志位置为false
                                isColorCameraFristDataCallback = true;

                                colorCameraUtils.setSurfaceTexture(surface);
                                //绑定摄像头
                                colorCameraUtils.attachCameraForSurfaceTexture();
                                //设置视频画面 左右镜像翻转
                                if (SystemUtils.isNeedOpenCameraMirrorFlipPreview()){
                                    Matrix transform = new Matrix();
                                    transform.setScale(-1, 1, colorCameraPreviewView.getWidth() / 2, 0);
                                    colorCameraPreviewView.setTransform(transform);
                                }
                                if (isNeedDataCallback) {
                                    //添加视频帧数据监听
                                    colorCameraUtils.setPreviewCallbackWithBuffer(colorCameraPreviewCallback);
                                }
                                //开始预览
                                colorCameraUtils.startCameraPreview();
                            }else{
                                //初始化结果为 执行初始化摄像头的cameraId的彩色黑白摄像头参数信息与 项目 CameraIdTypeUtils 类中获取到的彩色黑白摄像头的cameraId 不一致
                                if (initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_FAILURE_RETRY_CAMERAID_INFO_CONSISTENT_TIMEOUT){
                                    Log.e(TAG, "initColorCameraAndPreview:  彩色摄像头初始化异常，cameraId类型与传入的 不一致，" +
                                            "并且重新执行初始化流程已达到上线");
                                    showMsg("彩色摄像头初始化异常，cameraId类型与传入的 不一致,并且重新执行初始化流程已达到上线");
                                }else {
                                    Log.e(TAG, "initColorCameraAndPreview:  彩色摄像头初始化遭遇系统Expection异常或传入的cameraId下标大于设备摄像头数量");
                                    showMsg("彩色摄像头open遭遇Expection异常，执行USB摄像头复位操作");
                                    //重置USB摄像头
//                                    resetUsbCamera();
                                }
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            Log.e(TAG, "initColorCameraAndPreview: 彩色摄像头 初始化流程执行过程中 遭遇Expection异常:  " + e.getMessage());
                            showMsg("彩色摄像头 初始化流程执行过程中 遭遇Expection异常，执行USB摄像头复位操作");
                            //重置USB摄像头
//                            resetUsbCamera();
                        }

                        if (SystemUtils.isVankeSiteBoxDevice()){
                            //因万科智慧工地项目拥有3个摄像头，为避免多个摄像头在同一时刻打开导致系统服务冲突，
                            // 在彩色摄像头初始化完毕后，再开始 红外摄像头的初始化流程
                            initInfradCameraAndPreview(infradCameraPreviewView.getSurfaceTexture());
                        }
                    }
                });
    }

    /**
     * 定义一个方法用于初始化摄像头，并开启预览
     */
    @SuppressLint("CheckResult")
    private void initInfradCameraAndPreview(final SurfaceTexture surface) {
        Observable.just("")
                .observeOn(Schedulers.io())
                .map(s -> {
                    //初始化摄像头
                    infradCameraInitStartTime = System.currentTimeMillis();
                    Log.e(TAG, "apply: ----------开始执行 黑白摄像头初始化流程,执行的CameraId下标为： " + infradCameraUtils.getOpenCameraId()
                            + "  当前毫秒数：  " + infradCameraInitStartTime);
                    int initResult;
                    if (!SystemUtils.isVankeSiteBoxDevice()){           //普通设备
                        initResult = infradCameraUtils.initCamera();
                    }else {                                             //万科智慧工地项目设备
                        initResult = infradCameraUtils.initCamera(false);
                    }
                    infradCameraInitTime = System.currentTimeMillis() - infradCameraInitStartTime;
                    Log.e(TAG, "apply: ----------完成 黑白摄像头初始化流程。【【【总共耗时：  " + infradCameraInitTime);
                    return initResult;
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(initResult -> {
                    try {
                        Log.e(TAG, "accept: 黑白摄像头初始化结果：  " + initResult);
                        //如果摄像头初始化成功或者已经初始化过了，就执行预览流程
                        if (initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_INIT_SUCESS ||
                                initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_INITED){
                            //初始化摄像头成功，将标志位置为false
                            isInfradCameraFristDataCallback = true;

                            infradCameraUtils.setSurfaceTexture(surface);
                            //绑定摄像头
                            infradCameraUtils.attachCameraForSurfaceTexture();
                            //设置视频画面 左右镜像翻转
                            if (SystemUtils.isNeedOpenCameraMirrorFlipPreview()){
                                Matrix transform = new Matrix();
                                transform.setScale(-1, 1, infradCameraPreviewView.getWidth() / 2, 0);
                                infradCameraPreviewView.setTransform(transform);
                            }
                            if (isNeedDataCallback) {
                                //添加视频帧数据监听
                                infradCameraUtils.setPreviewCallbackWithBuffer(infradCameraPreviewCallback);
                            }
                            //开始预览
                            infradCameraUtils.startCameraPreview();
                        }else{
                            if (initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_FAILURE_RETRY_CAMERAID_INFO_CONSISTENT_TIMEOUT){
                                Log.e(TAG, "initColorCameraAndPreview:  黑白摄像头初始化异常，cameraId类型与传入的 不一致，" +
                                        "并且重新执行初始化流程已达到上线");
                                showMsg("黑白摄像头初始化异常，cameraId类型与传入的 不一致,并且重新执行初始化流程已达到上线");
                            }else {
                                Log.e(TAG, "initColorCameraAndPreview:  黑白摄像头初始化遭遇系统Expection异常或传入的cameraId下标大于设备摄像头数量");
                                showMsg("摄像头open遭遇Expection异常，执行USB摄像头复位操作");
                                //重置USB摄像头
//                                    resetUsbCamera();
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        Log.e(TAG, "initColorCameraAndPreview: 黑白摄像头 初始化流程执行过程中 遭遇Expection异常:  " + e.getMessage());
                        showMsg("黑白摄像头 初始化流程执行过程中 遭遇Expection异常，执行USB摄像头复位操作");
                        //重置USB摄像头
//                            resetUsbCamera();
                    }


                    if (SystemUtils.isVankeSiteBoxDevice()){
                        //因万科智慧工地项目拥有3个摄像头，为避免多个摄像头在同一时刻打开导致系统服务冲突，
                        // 在红外摄像头初始化完毕后，再开始 拍单摄像头的初始化流程
                        initTakePhotoCameraAndPreview(takePhotoCameraPreviewView.getSurfaceTexture());
                    }
                });
    }

    /**
     * 定义一个方法用于初始化摄像头，并开启预览
     */
    @SuppressLint("CheckResult")
    private void initTakePhotoCameraAndPreview(final SurfaceTexture surface) {
        Observable.just("")
                .observeOn(Schedulers.io())
                .map(s -> {
                    //初始化摄像头
                    takePhotoCameraInitStartTime = System.currentTimeMillis();
                    Log.e(TAG, "initTakePhotoCameraAndPreview: ----------开始执行 拍单摄像头初始化流程,执行的CameraId下标为： " + takePhotoCameraUtils.getOpenCameraId()
                            + "  当前毫秒数：  " + takePhotoCameraInitStartTime);
                    int initResult;
                    if (!SystemUtils.isVankeSiteBoxDevice()){           //普通设备
                        initResult = takePhotoCameraUtils.initCamera();
                    }else {                                             //万科智慧工地项目设备
                        initResult = takePhotoCameraUtils.initCamera(false);
                    }
                    takePhotoCameraInitTime = System.currentTimeMillis() - takePhotoCameraInitStartTime;
                    Log.e(TAG, "initTakePhotoCameraAndPreview: ----------完成 拍单摄像头初始化流程。【【【总共耗时：  " + takePhotoCameraInitTime);
                    return initResult;
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(initResult -> {
                    try {
                        Log.e(TAG, "initTakePhotoCameraAndPreview: 拍单摄像头初始化结果：  " + initResult);
                        //如果摄像头初始化成功或者已经初始化过了，就执行预览流程
                        if (initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_INIT_SUCESS ||
                                initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_INITED){
                            //初始化摄像头成功，将标志位置为false
                            isTakePhotoCameraFristDataCallback = true;

                            takePhotoCameraUtils.setSurfaceTexture(surface);
                            //绑定摄像头
                            takePhotoCameraUtils.attachCameraForSurfaceTexture();
                            //设置视频画面 左右镜像翻转
                            if (SystemUtils.isNeedOpenCameraMirrorFlipPreview()){
                                Matrix transform = new Matrix();
                                transform.setScale(-1, 1, takePhotoCameraPreviewView.getWidth() / 2, 0);
                                takePhotoCameraPreviewView.setTransform(transform);
                            }
                            if (isNeedDataCallback) {
                                //添加视频帧数据监听
                                takePhotoCameraUtils.setPreviewCallbackWithBuffer(takePhotoCameraPreviewCallback);
                            }
                            //开始预览
                            takePhotoCameraUtils.startCameraPreview();
                        }else{
                            if (initResult == TcTextureViewCameraUtils.CAMERA_OPERATE_RESULT_FAILURE_RETRY_CAMERAID_INFO_CONSISTENT_TIMEOUT){
                                Log.e(TAG, "initTakePhotoCameraAndPreview:  拍单摄像头初始化异常，cameraId类型与传入的 不一致，" +
                                        "并且重新执行初始化流程已达到上线");
                                showMsg("拍单摄像头初始化异常，cameraId类型与传入的 不一致,并且重新执行初始化流程已达到上线");
                            }else {
                                Log.e(TAG, "initTakePhotoCameraAndPreview:  拍单摄像头初始化遭遇系统Expection异常或传入的cameraId下标大于设备摄像头数量");
                                showMsg("摄像头open遭遇Exception异常");
                                //重置USB摄像头
//                                    resetUsbCamera();
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        Log.e(TAG, "initTakePhotoCameraAndPreview: 拍单摄像头 初始化流程执行过程中 遭遇Exception异常:  " + e.getMessage());
                        showMsg("拍单摄像头 初始化流程执行过程中 遭遇Exception异常： " + e.getMessage());
                        //重置USB摄像头
//                            resetUsbCamera();
                    }
                });
    }

    /**
     * 定义一个方法用于停止相机预览并注销摄像头
     */
    private void stopPreviewAndDestoryCamera() {
        //取消定时任务
        handler.removeMessages(MSG_COLOR_CAMERA_ERROR);
        handler.removeMessages(MSG_INFRARD_CAMERA_ERROR);
        handler.removeMessages(MSG_TAKE_PHOTO_CAMERA_ERROR);

        //停止彩色摄像头预览
        if (colorCameraUtils != null) {
            colorCameraUtils.stopCameraPreview();
            colorCameraUtils.destoryCamera();
        }

        //停止红外摄像头预览
        if (infradCameraUtils != null) {
            infradCameraUtils.stopCameraPreview();
            infradCameraUtils.destoryCamera();
        }

        //停止拍单摄像头预览
        if (takePhotoCameraUtils != null) {
            takePhotoCameraUtils.stopCameraPreview();
            takePhotoCameraUtils.destoryCamera();
        }

        //关闭红外补光灯
        LightControlUtils.getInstance().openOrCloseInfraredLight(false);

        isColorCameraFristDataCallback = true;
        isInfradCameraFristDataCallback = true;
        isTakePhotoCameraFristDataCallback = true;
    }

    private void resetState() {
        //移除Handler事件
        handler.removeMessages(REFRESH_COLOR_CAMERA_PARMA_INFO);
        handler.removeMessages(REFRESH_INFRAD_CAMERA_PARMA_INFO);
        handler.removeMessages(REFRESH_TAKE_PHOTO_CAMERA_PARMA_INFO);
        handler.removeMessages(REFRESH_CAMERA_CALLBACK_DATA_INFO);

        //重置参数信息
        colorCameraInitStartTime = 0;
        colorCameraInitTime = 0;
        colorCameraGetDataTime = 0;
        colorCameraInitTotalTime = 0;
        isColorCameraFristDataCallback = true;

        infradCameraInitStartTime = 0;
        infradCameraInitTime = 0;
        infradCameraGetDataTime = 0;
        infradCameraInitTotalTime = 0;
        isInfradCameraFristDataCallback = true;

        //重置控件状态
        colorCameraInitInfoTv.setText("");
        infradCameraInitInfoTv.setText("");
        colorCameraParmaTv.setText("");
        infradCameraParmaTv.setText("");
        colordelayTimeTv.setText("");
        infraddelayTimeTv.setText("");
    }

    private class ColorCameraPreviewCallback implements Camera.PreviewCallback {

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
//            Log.i(TAG, "onPreviewFrame: 获取到 【彩色】 摄像头 帧数据回调： " + data.length);
            //测试界面不发布彩色摄像头异常定时事件
//            postColorCameraErrorEvent();
            if (isColorCameraFristDataCallback) {
                //计算摄像头 【初始化结束】后 到 接收到第一帧数据回调 的执行时间
                colorCameraGetDataTime = System.currentTimeMillis() - colorCameraInitStartTime - colorCameraInitTime;
                //计算摄像头初始化耗时 总时间
                colorCameraInitTotalTime = colorCameraInitTime + colorCameraGetDataTime;
                //初始化成功，通知刷新摄像机初始化信息
                handler.sendEmptyMessage(REFRESH_CAMERA_INIT_INFO);
                //通知刷新数据回调长度
                handler.sendMessage(handler.obtainMessage(REFRESH_CAMERA_CALLBACK_DATA_INFO,
                        CAMERA_TYPE_COLOR,-1, data.length));
                //将标志位重置回false
                isColorCameraFristDataCallback = false;
            }else {
                //获取本帧视频数据的获取时间
                long currentDataTime = System.currentTimeMillis();
                //计算得出两帧之间的间隔时间
                long delayTime = currentDataTime - lastColorCameraPreviewDataTime;
                handler.sendMessage(handler.obtainMessage(REFRESH_COLOR_CAMERA_PARMA_INFO, delayTime));
                //刷新视频帧数据获取时间
                lastColorCameraPreviewDataTime = currentDataTime;
            }

            colorCameraUtils.addCallbackBuffer();
        }
    }

    private class InfradCameraPreviewCallback implements Camera.PreviewCallback {

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
//            Log.i(TAG, "onPreviewFrame: 获取到 【红外】 摄像头 帧数据回调： " + data.length);
            //测试界面不发布黑白摄像头异常定时事件
//            postInfrardCameraErrorEvent();
            if (isInfradCameraFristDataCallback) {
                //计算摄像头 【初始化结束】后 到 接收到第一帧数据回调 的执行时间
                infradCameraGetDataTime = System.currentTimeMillis() - infradCameraInitStartTime - infradCameraInitTime;
                //计算摄像头初始化耗时 总时间
                infradCameraInitTotalTime = infradCameraInitTime + infradCameraGetDataTime;
                //初始化成功，通知刷新摄像机初始化信息
                handler.sendEmptyMessage(REFRESH_CAMERA_INIT_INFO);
                //通知刷新数据回调长度
                handler.sendMessage(handler.obtainMessage(REFRESH_CAMERA_CALLBACK_DATA_INFO,CAMERA_TYPE_INFRARED,-1, data.length));
                //将标志位重置回false
                isInfradCameraFristDataCallback = false;
            }else {
                //获取本帧视频数据的获取时间
                long currentDataTime = System.currentTimeMillis();
                //计算得出两帧之间的间隔时间
                long delayTime = currentDataTime - lastInfradCameraPreviewDataTime;
                handler.sendMessage(handler.obtainMessage(REFRESH_INFRAD_CAMERA_PARMA_INFO, delayTime));
                //刷新视频帧数据获取时间
                lastInfradCameraPreviewDataTime = currentDataTime;
            }

            infradCameraUtils.addCallbackBuffer();

        }
    }

    private class TakePhotoCameraPreviewCallback implements Camera.PreviewCallback {

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
//            Log.i(TAG, "onPreviewFrame: 获取到 【拍单】 摄像头 帧数据回调： " + data.length);
            //测试界面不发布黑白摄像头异常定时事件
//            postTakePhotoCameraErrorEvent();
            if (isTakePhotoCameraFristDataCallback) {
                //计算摄像头 【初始化结束】后 到 接收到第一帧数据回调 的执行时间
                takePhotoCameraGetDataTime = System.currentTimeMillis() - takePhotoCameraInitStartTime - takePhotoCameraInitTime;
                //计算摄像头初始化耗时 总时间
                takePhotoCameraInitTotalTime = takePhotoCameraInitTime + takePhotoCameraGetDataTime;
                //初始化成功，通知刷新摄像机初始化信息
                handler.sendEmptyMessage(REFRESH_CAMERA_INIT_INFO);
                //通知刷新数据回调长度
                handler.sendMessage(handler.obtainMessage(REFRESH_CAMERA_CALLBACK_DATA_INFO,CAMERA_TYPE_TAKE_PHOTO,-1, data.length));
                //将标志位重置回false
                isTakePhotoCameraFristDataCallback = false;
            }else {
                //获取本帧视频数据的获取时间
                long currentDataTime = System.currentTimeMillis();
                //计算得出两帧之间的间隔时间
                long delayTime = currentDataTime - lastTakePhotoCameraPreviewDataTime;
                handler.sendMessage(handler.obtainMessage(REFRESH_TAKE_PHOTO_CAMERA_PARMA_INFO, delayTime));
                //刷新视频帧数据获取时间
                lastTakePhotoCameraPreviewDataTime = currentDataTime;
            }

            takePhotoCameraUtils.addCallbackBuffer();
        }
    }

    /**
     * 定义一个方法用于发布彩色摄像头错误超时事件
     */
    private void postColorCameraErrorEvent() {
        //发布前先取消上次的超时事件
        handler.removeMessages(MSG_COLOR_CAMERA_ERROR);
        handler.sendEmptyMessageDelayed(MSG_COLOR_CAMERA_ERROR,CAMERA_ERROR_TIMEOUT_TIME);
//        Log.i(TAG, "postColorCameraErrorEvent: 发布 彩色摄像头错误超时事件----");
    }

    /**
     * 定义一个方法用于发布黑白摄像头错误超时事件
     */
    private void postInfrardCameraErrorEvent() {
        //发布前先取消上次的超时事件
        handler.removeMessages(MSG_INFRARD_CAMERA_ERROR);
        handler.sendEmptyMessageDelayed(MSG_INFRARD_CAMERA_ERROR,CAMERA_ERROR_TIMEOUT_TIME);
    }

    /**
     * 定义一个方法用于发布拍单摄像头错误超时事件
     */
    private void postTakePhotoCameraErrorEvent() {
        //发布前先取消上次的超时事件
        handler.removeMessages(MSG_TAKE_PHOTO_CAMERA_ERROR);
        handler.sendEmptyMessageDelayed(MSG_TAKE_PHOTO_CAMERA_ERROR,CAMERA_ERROR_TIMEOUT_TIME);
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_CAMERA_INIT_INFO: {
                    colorCameraInitInfoTv.setText(String.format("彩色摄像头初始化耗时: %d ms " +
                            "\n获取到视频数据耗时: %d ms" +
                            "\n总耗时: %d ms", colorCameraInitTime, colorCameraGetDataTime, colorCameraInitTotalTime));

                    infradCameraInitInfoTv.setText(String.format("红外摄像头初始化耗时: %d ms " +
                            "\n获取到视频数据耗时: %d ms" +
                            "\n总耗时: %d ms", infradCameraInitTime, infradCameraGetDataTime, infradCameraInitTotalTime));

                    takePhotoCameraInitInfoTv.setText(String.format("拍单摄像头初始化耗时: %d ms " +
                            "\n获取到视频数据耗时: %d ms" +
                            "\n总耗时: %d ms", takePhotoCameraInitTime, takePhotoCameraGetDataTime, takePhotoCameraInitTotalTime));
                    break;
                }
                case REFRESH_COLOR_CAMERA_PARMA_INFO: {
                    long delayTime = (long) msg.obj;
                    float frameRate = (float) 1000 / (float) delayTime;
                    colordelayTimeTv.setText("两帧数据间隔时间：" + delayTime + " ms" + "\n" +
                            String.format("%.2f", frameRate) + " 帧/秒");
                    break;
                }
                case REFRESH_INFRAD_CAMERA_PARMA_INFO: {
                    long delayTime = (long) msg.obj;
                    float frameRate = (float) 1000 / (float) delayTime;
                    infraddelayTimeTv.setText("两帧数据间隔时间：" + delayTime + " ms" + "\n" +
                            String.format("%.2f", frameRate) + " 帧/秒");
                    break;
                }
                case REFRESH_TAKE_PHOTO_CAMERA_PARMA_INFO: {
                    long delayTime = (long) msg.obj;
                    float frameRate = (float) 1000 / (float) delayTime;
                    takePhotoDelayTimeTv.setText("两帧数据间隔时间：" + delayTime + " ms" + "\n" +
                            String.format("%.2f", frameRate) + " 帧/秒");
                    break;
                }
                case REFRESH_CAMERA_CALLBACK_DATA_INFO: {
                    int dataLength = (int) msg.obj;
                    if (msg.arg1 == CAMERA_TYPE_COLOR){
                        Camera.Size colorPreviewSize = colorCameraUtils.getPreviewSize();
                        if (colorPreviewSize != null){
                            colorCameraParmaTv.setText("相机数据回调长度： " + dataLength + "\n" +
                                    "预览分辨率： " + colorPreviewSize.width + " * " + colorPreviewSize.height + "\n");
                        }
                    }else if (msg.arg1 == CAMERA_TYPE_INFRARED){
                        Camera.Size infradPreviewSize = infradCameraUtils.getPreviewSize();
                        if (infradPreviewSize != null){
                            infradCameraParmaTv.setText("相机数据回调长度： " + dataLength + "\n" +
                                    "预览分辨率： " + infradPreviewSize.width + " * " + infradPreviewSize.height + "\n");
                        }
                    }else if (msg.arg1 == CAMERA_TYPE_TAKE_PHOTO){
                        Camera.Size takePhotoPreviewSize = takePhotoCameraUtils.getPreviewSize();
                        if (takePhotoPreviewSize != null){
                            takePhotoCameraParmaTv.setText("相机数据回调长度： " + dataLength + "\n" +
                                    "预览分辨率： " + takePhotoPreviewSize.width + " * " + takePhotoPreviewSize.height + "\n");
                        }
                    }
                    break;
                }

                case MSG_COLOR_CAMERA_ERROR:{
                    Log.e(TAG, "handleMessage: 【彩色摄像头出现异常】，关闭摄像头并重新开启-----");
                    showMsg("【彩色摄像头无法接收到视频数据】，关闭摄像头并重新开启");
                    //收到彩色摄像头异常事件时必须移除 另外一种摄像头的错误异常事件，防止同时发布错误信息导致错乱
                    handler.removeMessages(MSG_INFRARD_CAMERA_ERROR);
                    //停止预览并注销摄像头
                    stopPreviewAndDestoryCamera();
                    //开始摄像头预览
                    startPreview();
                    break;
                }

                case MSG_INFRARD_CAMERA_ERROR:{
                    Log.e(TAG, "handleMessage: 【黑白摄像头出现异常】，关闭摄像头并重新开启-----");
                    showMsg("【黑白摄像头无法接收到视频数据】，关闭摄像头并重新开启");
                    //收到黑白摄像头异常事件时必须移除 另外一种摄像头的错误异常事件，防止同时发布错误信息导致错乱
                    handler.removeMessages(MSG_COLOR_CAMERA_ERROR);
                    //停止预览并注销摄像头
                    stopPreviewAndDestoryCamera();
                    //开始摄像头预览
                    startPreview();
                    break;
                }

                case MSG_TAKE_PHOTO_CAMERA_ERROR:{
                    Log.e(TAG, "handleMessage: 【拍单摄像头出现异常】，关闭摄像头并重新开启-----");
                    showMsg("【拍单摄像头无法接收到视频数据】，关闭摄像头并重新开启");
                    //收到黑白摄像头异常事件时必须移除 另外一种摄像头的错误异常事件，防止同时发布错误信息导致错乱
                    handler.removeMessages(MSG_COLOR_CAMERA_ERROR);
                    //停止预览并注销摄像头
                    stopPreviewAndDestoryCamera();
                    //开始摄像头预览
                    startPreview();
                    break;
                }
            }
            return false;
        }
    });

    /**
     * 定义一个内部类用于进行 彩色摄像头的TextureView的状态监听
     */
    private class ColorCameraTextureListener implements TextureView.SurfaceTextureListener {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            //停止预览并注销摄像头
            stopPreviewAndDestoryCamera();
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    }

    /**
     * 定义一个内部类用于进行 红外摄像头的TextureView的状态监听
     */
    private class InfradCameraTextureListener implements TextureView.SurfaceTextureListener {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            //停止预览并注销摄像头
            stopPreviewAndDestoryCamera();
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    }

    private class TakePhotoCameraTextureListener implements TextureView.SurfaceTextureListener {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            //停止预览并注销摄像头
            stopPreviewAndDestoryCamera();
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    }

}
